requirejs(['jquery', 'pageJs','config', 'arttemplateUtil','common','msg_util','validform','area','calendar','wdatePicker','bootstrap_typeahead'], function($, pageJs,config, arttemplateUtil,common,msg_util) {
	var param = {order_tab:0}
	var user_data = {operator:"",operator_num:""}
	var initData = function(){
		common.loading();
		common.common_ajax_request('/api/seller/v1/quyerSubcribeList',param,true,function(data,code,msg){
			if(msg.businessCode==0){
				setData(data);
				$("#sub_all_count").html(data.allCount);
				$("#sub_serch_count").html(data.totalCount);
				$("#sub_percent").html(data.percent);
				user_data.operator=data.operator;
				user_data.operator_num=data.operator_num;
				pageJs.setPage(data.pageNo,data.totalPage,data.totalCount,callback);
			}else{
				setData({});
				window.layer.msg("系统异常");
			}
			layer.closeAll('loading'); //关闭加载层
		},"","post");
	}
	var subscribe_tpl;//订单列表模板
	var calendar_tpl;//日历模板
	var delivery_date_tpl;//配送时间模板
	var subscribe_addr_tpl;//配送地址修改
	var delivery_num_tpl;//修改剩余配送次数
	var delivery_pilv_tpl;//修改配送频率
	var delivery_memo_tpl;//用户备注修改
	var delivery_list_tpl;//查看修改记录
	var delivery_consume_tpl;//消费习惯
	var delivery_send_tpl;//配送需求
	
	var initTpl = function(){
		subscribe_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/subscribe_tpl.html'));
		calendar_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/calendar_tpl.html'));
		delivery_date_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/delivery_date_tpl.html'));
		subscribe_addr_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/subscribe_addr_tpl.html'));
		delivery_num_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliver_num_tpl.html'));
		delivery_pilv_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliver_pilv_tpl.html'));
		delivery_memo_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliver_memo_tpl.html'));
		delivery_list_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliver_list_tpl.html'));
		//delivery_consume_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliver_consume_tpl.html'));
		//delivery_send_tpl = arttemplateUtil.template.compile($.setHTML('order/templates/deliver_send_tpl.html'));
	}
	
	//订单列表
	var setData = function(data){
		var res = {
				order_tab:param.order_tab,
				records:data.records,
				url:config.imgRoot()
		}
		$("#orderlist").html(subscribe_tpl(res));
	}
	
	var callback = function(page){
		param.pageNo=page
		initData();
	}
	
	var init = function() {
		arttemplateUtil.auload();
		$.each($('#serchForm').serializeArray(), function(i, item) {
			if(item.value==""){
				delete param[item.name]
			}else{
				param[item.name]=item.value;
			}
		});
		initTpl();
		initData();
		autoComplete();
		
	};
	var validserchform = $("#serchForm").Validform({
		tiptype:4,
		postonce:true,
		isShowRight:false,
		datatype:{"numCompare":function(gets,obj,curform,regxp){
			var minnum = $.trim($("#serchForm input[name=first_remain_num]").val());
			var maxnum = $.trim($("#serchForm input[name=last_remain_num]").val());
			var reg = /^[1-9]\d{1,7}$|^[0-9]$/;
			if( (minnum !="" && !reg.test(minnum)) || (maxnum !="" && !reg.test(maxnum))) {
				return "剩余配送次数范围为[0-99999999]";
			}

			if( minnum !="" && maxnum !="") {
				if (parseInt(maxnum) < parseInt(minnum)) {
					return "开始剩余配送次数必须小于结束剩余配送次数";
				}
			}
			$("#serchForm input[name=first_remain_num]").removeClass("Validform_error");
			$("#serchForm input[name=last_remain_num]").removeClass("Validform_error");
			return true;
		}}
	});
	
	//页签选择
	$('#tabs-632335 a').click(function (e) {
		param.order_tab=$(this).attr("tab_value");
		param.pageNo=1;
		initData();
	});
	//批量调整计划
	$(document).off('click','.canclePlanBtn').on('click','.canclePlanBtn',function(event){
		$('#myModalLabel').modal('show');
		$("#dialog_tpl").html(arttemplateUtil.template.compile($.setHTML('order/templates/cancle_plan_tpl.html')));
	});
	
	$(document).off('click','.canclePlanSubmit').on('click','.canclePlanSubmit',function(event){
			var validaddrForm = $("#canclePlanForm").Validform({
				tiptype:4,
				postonce:true,
				isShowRight:false
			});
			if(!validaddrForm.check()){
				return false;
			}
		   $(this).attr("disabled","disabled");
		    common.loading();
			common.common_ajax_request('/api/seller/v1/batchCanclePlanForDate',$('#canclePlanForm').serializeArray(),false,function(data,code,msg){
				   layer.msg(msg.businessNote);
				   if(msg.businessCode==0){
					   $('#myModalLabel').modal('hide');
				   }
				   layer.closeAll('loading');
			},"","get",function(){
				$(".canclePlanSubmit").removeAttr("disabled");
			});
	});
	//消息提示
	$(document).off('click','.mesInfo').on('click','.mesInfo',function(event){
		//取消事件冒泡  
	    event.stopPropagation();  
		messageDialog(this);
	});
	//调整计划
	$(document).off('click','.planBtn').on('click','.planBtn',function(){
		var id = $(this).attr("data-id");
		var of_id = $(this).attr("data-order-id");
		var force_type = $(this).attr("data-force");
		var deliveryNoStandard = false;
		if(force_type==1){
			deliveryNoStandard = true;
		}
		common.loading();
		common.common_ajax_request('/api/seller/v1/queryPlan',{id:of_id,force_type:force_type},false,function(data,code,msg){
			if(msg.businessCode==0){
				$('#myModalLabel').modal('show');
				var res = {
						period_id:of_id,
						force_type:force_type
				}
				$("#dialog_tpl").html(calendar_tpl(res));
		        $("#calendarDiv").calendarpicker({
			            value: [data.curDate],
			            calendarData:data.detailsList,
			            deliver_status:[
			                {"deliver_status":1,"deliver_name":"正常配送"},
			                {"deliver_status":2,"deliver_name":"已配送"},
			                {"deliver_status":3,"deliver_name":"暂停配送"}
			            ],
			            deliveryNoStandard:deliveryNoStandard,
			            onDayClick:function(p,day,data_date){
			                if($(day).attr("data-modify_timeout")=="true"){
			                	window.layer.msg("只能修改超出36小时的配送")
			                }
			        	}
				});
			}else{
				window.layer.msg(msg.businessNote);
			}
			layer.closeAll('loading');
		},"","post");
	});
	
   $(document).off('click','.planSubmit').on('click','.planSubmit',function(){
	   var id = $("#period_id").val();
	   var data = $("#calendarDiv").attr("data-values");
	   var force_type = $("#force_type").val();
	   if(data == undefined || data ==""){
		   window.layer.msg("配送计划无改变");
		   $('#myModalLabel').modal('hide');
	   }else{
			var validPlanform = $("#planForm").Validform({
				tiptype:4,
				postonce:true,
				isShowRight:false
			});
		   if(!validPlanform.check()){
			   return false;
		   }
		   
		   $(this).attr("disabled","disabled");
		    common.loading();
			common.common_ajax_request('/api/seller/v1/editPlan',{of_id:id,data:data,force_type:force_type,reason:$("#reason").val()},false,function(data,code,msg){
				   layer.msg(msg.businessNote);
				   if(msg.businessCode==0){
					   $('#myModalLabel').modal('hide');
				   }
				   layer.closeAll('loading');
			},"","get",function(){
				$(".planSubmit").removeAttr("disabled");
			});
	   }
	   
   });
	
  //查询
  $('.serchBtn').on('click',function(){
	  if(validserchform.check()){
		param.pageNo=1;
		delete param["isNew"];
		$.each($('#serchForm').serializeArray(), function(i, item) {
			if(item.value==""){
				delete param[item.name]
			}else{
				param[item.name]=item.value;
			}
		})
		initData();
  	  }
   });
   
   //重置
   $('.resetBtn').on('click',function(){
		$.each($('#serchForm').serializeArray(), function(i, item) {
			delete param[item.name];
		});
		delete param["isNew"];
		$('#serchForm')[0].reset();
		//$("form[name=serchForm] input").val("");
		$("#serchForm input").removeClass("Validform_error");
		$("#serchForm .Validform_checktip").removeClass("Validform_wrong").html("");
		//$("#serchForm input[name=isNew]").prop("checked",false);
		initData();
	});
   
	//导出
	$('.excelBtn').on('click',function(){
		$("#excel").attr("action",config.apiRoot()+"/api/seller/v1/excelSubcribeList");
		var html = [];
		html.push("<input name=\"order_tab\" type='hidden' id=\"order_tab\" value=\""+param.order_tab+"\" />");
		$.each($('#serchForm').serializeArray(), function(i, item) {
			html.push("<input name=\""+item.name+"\" type='hidden' id=\""+item.name+"\" value=\""+item.value+"\" />");
		});
		$.each(config.setFullParameterArr({}), function(i, item) {
			html.push("<input name=\""+i+"\" type='hidden' id="+i+" value=\""+item+"\" />");
		});
		$("#excel").html(html.join(""));
		$("#excel").submit();
	});
	
	//修改剩余配送次数
	$(document).off('click','.numsBtn').on('click','.numsBtn',function(){
		var surplus_times = $(this).attr("data-surplus-times");
		var of_id = $(this).attr("data-id");
		var res = {
				of_id:of_id,
				surplus_times:surplus_times,
				operator:user_data.operator,
				operator_num:user_data.operator_num
		}
		$('#myModalLabel').modal('show');
		$('#dialog_tpl').html(delivery_num_tpl(res));
	});
	//剩余配送次数保存
	$(document).off('click','.numSubmit').on('click','.numSubmit',function(){
		var validaddrForm = $("#datanumForm").Validform({
			tiptype:4,
			postonce:true,
			isShowRight:false,
			datatype:{"numCompare":function(gets,obj,curform,regxp){
				var reg = /^[1-9]\d{1,7}$|^[0-9]$/;
				if($(obj).val() =="" || !reg.test($(obj).val())) {
					return "剩余配送次数范围为[0-99999999]";
				}
				$("#datanumForm input[name=surplus_times]").removeClass("Validform_error");
				$("#datanumForm input[name=Validform_checktip]").removeClass("Validform_error");
				$(obj).next().remove();
				return true;
			}}
		});
		
		if($("#old_surplus_times").val()==$("#surplus_times").val()){
			window.layer.msg("剩余配送次数无修改");
			return false;
		}
		
		if(!validaddrForm.check()){
			return false;
		}
		
		var r = function(){
			common.loading();
			$(this).attr("disabled","disabled");
			common.common_ajax_request('/api/seller/v1/saveSurplus',$('#datanumForm').serializeArray(),false,function(data,code,msg){
				window.layer.msg(msg.businessNote);
				if(msg.businessCode==0){
					$('#myModalLabel').modal('hide');
					initData();
				}
				layer.closeAll('loading');
			},"","post",function(){
				$(".numSubmit").removeAttr("disabled");
			});
		} 
		
		//询问框
		if($("#datanumForm input[name=surplus_times]").val()==0){
			layer.confirm('是否这样修改，修改后则此订阅为已完成状态？', {
				  btn: ['确定','取消'] //按钮
				}, function(){
				  r();
				}, function(){
				  
				});
		}else{
			r();
		}

	});
	//修改配送频率
	$(document).off('click','.pilvBtn').on('click','.pilvBtn',function(){
		var id = $(this).attr("data-order-id");
		var frequency = $(this).attr("data-frequency-type");
		var res = {
				id:id,
				operator:user_data.operator,
				operator_num:user_data.operator_num
		}
		$('#myModalLabel').modal('show');
		$('#dialog_tpl').html(delivery_pilv_tpl(res));
		$("#frequency option[value="+frequency+"]").attr("selected",true);
		
	});
	//修改配送频率保存
	$(document).off('click','.pilvSubmit').on('click','.pilvSubmit',function(){
		var validaddrForm = $("#frequencycombForm").Validform({
			tiptype:4,
			postonce:true,
			isShowRight:false
		});
		if(!validaddrForm.check()){
			return false;
		}
		$(this).attr("disabled","disabled");
		var r = function(){
			var url = '/api/seller/v1/savePilv';
			if($("#frequency").val()=="0"){//暂停
				url = '/api/seller/v1/pauseService';
			}
			common.loading();
			common.common_ajax_request(url,$('#frequencycombForm').serializeArray(),false,function(data,code,msg){
				window.layer.msg(msg.businessNote);
				if(msg.businessCode==0){
					$('#myModalLabel').modal('hide');
					initData();
				}
				layer.closeAll('loading');
			},"","post",function(){
				$(".pilvSubmit").removeAttr("disabled");
			});
		}
		
		r();

	});
	
	//修改配送要求
	$(document).off('click','.distributionBtn').on('click','.distributionBtn',function(){
		var distribution = $(this).attr("data-distribution");
		var id = $(this).attr("data-id");
		var res = {
				id:id,
				operator:user_data.operator,
				operator_num:user_data.operator_num
		}
		if(remark==undefined){
			res.name="新增配送需求";
			res.distribution="";
			res.reason="新增原因";
		}else{
			res.name="配送需求修改";
			res.distribution=distribution;
			res.reason="修改原因";
		}
		$('#myModalLabel').modal('show');
		$('#dialog_tpl').html(delivery_send_tpl(res));

	});
	
	
	//修改消费习惯
	$(document).off('click','.consumeBtn').on('click','.consumeBtn',function(){
		var consumption = $(this).attr("data-consumption");
		var id = $(this).attr("data-id");
		var res = {
				id:id,
				operator:user_data.operator,
				operator_num:user_data.operator_num
		}
		if(consumption==undefined){
			res.name="新增消费习惯";
			res.consumption="";
			res.reason="新增原因";
		}else{
			res.name="消费习惯修改";
			res.consumption=consumption;
			res.reason="修改原因";
		}
		$('#myModalLabel').modal('show');
		$('#dialog_tpl').html(delivery_consume_tpl(res));

	});
	
	//修改消费习惯
	$(document).off('click','.consumeSubmit').on('click','.consumeSubmit',function(){
		var validaddrForm = $("#consumeForm").Validform({
			tiptype:4,
			postonce:true,
			isShowRight:false
		});
		if(!validaddrForm.check()){
			return false;
		}
		
		var r = function(){
			$(this).attr("disabled","disabled");
			common.loading();
			common.common_ajax_request('/api/seller/v1/saveConsumption',$('#consumeForm').serializeArray(),false,function(data,code,msg){
				window.layer.msg(msg.businessNote);
				if(msg.businessCode==0){
					$('#myModalLabel').modal('hide');
					initData();
				}
				layer.closeAll('loading');
			},"","post",function(){
				$(".consumeSubmit").removeAttr("disabled");
			});
		}
		
		r();

	});
	
	var $data_config = {"1":["新增用户备注","新增原因","备注内容","1"],
			   "2":["用户备注修改","修改原因","备注内容","1"],
			   "3":["新增消费习惯","新增原因","消费习惯","2"],
			   "4":["消费习惯修改","修改原因","消费习惯","2"],
			   "5":["新增配送需求","新增原因","配送需求","3"],
			   "6":["配送需求修改","修改原因","配送需求","3"]
	
	}
	//修改备注
	$(document).off('click','.memoBtn').on('click','.memoBtn',function(){
		var remark = $(this).attr("data-remark");
		var data_type = $(this).attr("data-type");
		var id = $(this).attr("data-id");
		var res = {
				id:id,
				operator:user_data.operator,
				operator_num:user_data.operator_num,
				data_type:$data_config[data_type][3],
				name:$data_config[data_type][0],
				reason:$data_config[data_type][1],
				context_name:$data_config[data_type][2]
		}
		if(remark==undefined){
			res.remark="";
		}else{
			res.remark=remark;
		}
		$('#myModalLabel').modal('show');
		$('#dialog_tpl').html(delivery_memo_tpl(res));

	});
	
	//修改备注保存
	$(document).off('click','.memoSubmit').on('click','.memoSubmit',function(){
		var validaddrForm = $("#memoForm").Validform({
			tiptype:4,
			postonce:true,
			isShowRight:false
		});
		if(!validaddrForm.check()){
			return false;
		}
		
		var r = function(){
			$(this).attr("disabled","disabled");
			common.loading();
			common.common_ajax_request('/api/seller/v1/saveMemo',$('#memoForm').serializeArray(),false,function(data,code,msg){
				window.layer.msg(msg.businessNote);
				if(msg.businessCode==0){
					$('#myModalLabel').modal('hide');
					initData();
				}
				layer.closeAll('loading');
			},"","post",function(){
				$(".memoSubmit").removeAttr("disabled");
			});
		}
		
		r();

	});
	//查看日志记录
	$(document).off('click','.listBtn').on('click','.listBtn',function(){
			var alter_type = $(this).attr("data-alter-type");
			var order_id = $(this).attr("data-order-id");
			common.common_ajax_request('/api/seller/v1/queryOperateLog',{of_id:order_id,alter_type:alter_type},false,function(data,code,msg){
				if(msg.businessCode==0){
					$('#myModalLabel').modal('show');
					$('#dialog_tpl').html(delivery_list_tpl(data));
				}else{
					window.layer.msg(msg.businessNote);
				}
			},"","post");
	});
	
	//配送时间编辑
	$(document).off('click','.timesBtn').on('click','.timesBtn',function(){
		var goods_id = $(this).attr("data-goods-id");
		var id = $(this).attr("data-id");
		var times = $(this).attr("data-times");
		common.common_ajax_request('/api/seller/v1/queryFrequency',{goods_id:goods_id},false,function(data,code,msg){
			if(msg.businessCode==0){
				if(data.length>0){
					$('#myModalLabel').modal('show');
					var res = {
							data:data,
							id:id,
							times:times,
							operator:user_data.operator,
							operator_num:user_data.operator_num
					}
					$('#dialog_tpl').html(delivery_date_tpl(res));
				}else{
					window.layer.msg("不存在可修改的配送时间");
				}

			}else{
				window.layer.msg(msg.businessNote);
			}
		},"","post");
	});

	//配送时间保存
	$(document).off('click','.timesSubmit').on('click','.timesSubmit',function(){
		var validaddrForm = $("#delivery_date").Validform({
			tiptype:4,
			postonce:true,
			isShowRight:false
		});
		if(!validaddrForm.check()){
			return false;
		}
		$(this).attr("disabled","disabled");
		common.loading();
		var delivery_date_param = $('#delivery_date').serializeArray();
		delivery_date_param.push({"name":"frequency_text","value":$("#frequency_id").find("option:selected").text()});
		common.common_ajax_request('/api/seller/v1/saveFrequency',delivery_date_param,false,function(data,code,msg){
			window.layer.msg(msg.businessNote);
			if(msg.businessCode==0){
				$('#myModalLabel').modal('hide');
				initData();
			}
			layer.closeAll('loading');
		},"","post",function(){
			$(".timesSubmit").removeAttr("disabled");
		});
	});
	//修改地址
	$(document).off('click','.addrBtn').on('click','.addrBtn',function(){
		var id = $(this).attr("data-id");
		common.common_ajax_request('/api/seller/v1/quyerOrderAddrAndArea',{order_id:id},false,function(data,code,msg){
			
			if(msg.businessCode==0){
				$('#myModalLabel').modal('show');
				var res = {
					data:data,
					operator:user_data.operator,
					operator_num:user_data.operator_num
				}
				$('#dialog_tpl').html(subscribe_addr_tpl(res));

				$("#areaSelect").initAreaSelect();
			}else{
				window.layer.msg(msg.businessNote);
			}
		});
	});
	//修改地址提交保存
	$(document).off('click','.addrSubmit').on('click','.addrSubmit',function(){
		var validaddrForm = $("#addrForm").Validform({
			tiptype:4,
			postonce:true,
			isShowRight:false
		});
		var area_info = "";//地址
		var c_id = "";
		var c_name = "";
		var addr_param = {};
		$("#areaSelect").find('li select').each(function(i,value){
			if($(value).attr("level")==0){
				addr_param.province_name=$(value).find("option:selected").text();
			}else if($(value).attr("level")==1){
				addr_param.city_name=$(value).find("option:selected").text();
			}else if($(value).attr("level")==2){
				addr_param.county_name=$(value).find("option:selected").text();
			}else if($(value).attr("level") == 3){
				c_id = $(value).val();
				c_name = $(value).find("option:selected").text();
			}
        });
		if(c_id==undefined || c_id==""){
			window.layer.msg("请选择小区");
			return false;
		}
		if(!validaddrForm.check()){
			return false;
		}
		$(this).attr("disabled","disabled");
		addr_param.of_id=$("#of_id").val();
		addr_param.id=$("#id").val();
		addr_param.true_name=$("#true_name").val()
		addr_param.mobile=$("#mobile").val();
		addr_param.community_id=c_id;
		addr_param.community_name=c_name;
		addr_param.addr_details=$("#addr_details").val();
		addr_param.reason=$("#reason").val();
//		addr_param.operator=$("#operator").val();
//		addr_param.operator_num=$("#operator_num").val();
		common.common_ajax_request(
				'/api/seller/v1/saveOrderAddr',
				addr_param,
				true,function(data,code,msg){
					if(msg.businessCode==0){
						$('#myModalLabel').modal('hide');
						window.layer.msg("地址修改成功");
						initData();
					}else{
						window.layer.msg(msg.businessNote);
					}
				},"","post",function(){
					$(".addrSubmit").removeAttr("disabled");
				});
	});
	
	//消息提示
	$(document).off('click','.mesInfo').on('click','.mesInfo',function(event){
		//取消事件冒泡  
	    event.stopPropagation();  
	    msg_util.msgDialog(this,function(){
	    	initData();
	    });
	});
	//搜索自动补全;给搜索框注册自动联想完成事件
	var autoComplete = function(){
			jQuery('#service_name').typeahead({
				source: function (query, process) {
					//query是输入值
					if(query !== 'undefined' && typeof query != 'undefined' && query !==""){
						common.ajax_request2('post','/api/seller/v1/queryGoodsListByGoodsName', { "goods_name": query,goods_label:2}, function ($data,$code) {
							if($code==200){
								process($data);
							}
							
						});
					}else{
						process({});
					}
				},
				matcher:function(item){
					return true;
				},
				updater: function (item) {
					return item; //这里一定要return，否则选中不显示
				},
				afterSelect: function (item) {
					//选择项之后的时间，item是当前选中的项
					//alert(item);
				},
				items: 10, //显示8条
				delay: 500, //延迟时间
				autoSelect:true
			});
	};
	init();
	
});
